<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/12
 * Time: 11:40
 */
namespace App\Repositories;

use App\Models\Popup;

class PopupRepository
{
    public function byId($id)
    {
        return Popup::find($id);
    }
    public function getList($position)
    {
        $list = Popup::where([
            'is_open' => 1,
            'position' => $position,
        ])
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'asc')
            ->get();
        $data = [];
        foreach ($list as $key=>$value) {
            if ($value['start_date'] <= time() && time() <= $value['end_date']) {
                $data[$key] = $value;
                $data[$key]['img_url'] = !empty($value['img_url']) ? getOssImageUrl($value['img_url']) : '';
            }
        }
        return $data;
    }

    public function getPopupList($request)
    {
        $page = $request->pageNumber - 1;
        $page = $page < 0 ? 0 : $page;
        $limit = $request->pageSize ? $request->pageSize : 50;
        $offset = $page * $limit;
        $query = Popup::where(function ($query) use ($request) {
            if (!empty($request->position)) {
                $query->where('position', $request->position);
            }
            if (!is_null($request->url_type)) {
                $query->where('url_type', $request->url_type);
            }
            if (!is_null($request->is_open)) {
                $query->where('is_open', $request->is_open);
            }
            if (!is_null($request->title)) {
                $query->where('title', 'like', '%' . $request->title . '%');
            }
        });
        $total = $query->count();
        $result = $query->latest('id')
            ->offset($offset)
            ->limit($limit)
            ->get();
        return ['result' => $result, 'count' => $total];
    }

    public function create(array $param)
    {
        return Popup::create($param);
    }

    public function update($id, $param)
    {
        return Popup::where('id', $id)->update($param);
    }

    public function destroy($id)
    {
        return Popup::where('id', $id)->delete();
    }
}